package com.leetcode.tree.traversal;

import com.leetcode.basic.TreeNode;

import java.util.*;

/**
 * @author Dennis Li
 * @date 2020/6/16 21:27
 */
public class PostorderTraversal_145 {

    public List<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node == null) continue;
            // 这样的输出顺序是：根 -> 右 -> 左
            list.add(node.val);
            stack.push(node.left);
            stack.push(node.right);
        }
        // 精髓！ -- 换一种思路来解题 -- 通过一个方向相反的近似解，最后在答案基础上做反转
        // 反转结果，得到 ： 左 -> 根 -> 右
        Collections.reverse(list);
        return list;
    }

    public List<Integer> post(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if(root == null) return list;
        Deque<TreeNode> stack = new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.add(node.val);
            if (node.left != null) stack.push(node.left);
            if (node.right != null) stack.push(node.right);
        }
        Collections.reverse(list);
        return list;
    }

}
